#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy.orm import Session

from backend.app.crud import article_crud
from backend.app.model import Comment
from backend.app.schema.comment import CreateComment


def get_comment(db: Session) -> bool:
    return db.query(Comment)


def get_comment_by_id(db: Session, comment_id: int) -> bool:
    return db.query(Comment).filter(Comment.id == comment_id).first()


def get_comments(db: Session, article_id: int) -> list:
    return db.query(Comment).filter_by(article_id=article_id).order_by(Comment.create_time.desc()).all()


def get_comments_count(db: Session, article_id: int) -> int:
    return db.query(Comment).filter_by(article_id=article_id).count()


def get_comments_by_article_id(db: Session, article_id: int) -> list:
    return db.query(Comment).order_by(Comment.create_time.desc()).filter(Comment.article_id == article_id).all()


def get_new_comment(db: Session) -> list:
    return db.query(Comment).order_by(Comment.create_time.desc()).all()[0:8]


def create_comment(db: Session, post: CreateComment, article_id: int) -> Comment:
    title = article_crud.get_article_title(db, article_id)
    comment = Comment(**post.dict(), title=title, article_id=article_id)
    db.add(comment)
    db.commit()
    db.refresh(comment)
    return comment


def delete_comment(db: Session, pic_id: int) -> bool:
    pic_obj = db.query(Comment).filter(Comment.id == pic_id)
    pic_obj.delete()
    db.commit()
    return pic_obj.first()
